<?php

class Application_Model_AdminMapper
{
    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_Admin');
        }
        return $this->_dbTable;
    }

    public function find($id, Application_Model_Admin $admin)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $admin->setId($row->id)
              ->setEmail($row->email)
              ->setLogin($row->login)
              ->setFname($row->fname)
              ->setLastAccess($row->last_access)
              ->setLname($row->lname);
        return $admin;
    }

    public function findByLoginAndPassword($login, $password)
    {
        $table = $this->getDbTable();
        if ($table)
        {
            $select = $table->select()->where('login = ?', $login)->where('password = ?', MD5($password));
            $row    = $table->fetchRow($select);
            if (!empty($row->id))
            {
                $admin = new Application_Model_Admin();
                $admin->setId($row->id)
                      ->setEmail($row->email)
                      ->setLogin($row->login)
                      ->setFname($row->fname)
                      ->setLastAccess($row->last_access)
                      ->setLname($row->lname);
                return $admin;
            }
        }
        return false;
    }

    public function updateLastAccess($id)
    {
        $data = array(
            'last_access' => new Zend_Db_Expr('NOW()')
        );
        $table = $this->getDbTable();
        if ($table && $id > 0)
        {
            $where = 'id = ' . intval($id);
            $table->update($data, $where);
        }
    }
}